package com.example.elm_server_api.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 处理无权请求
 * @author charlie
 *
 */
@Component
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    /**
     *
     * @param request
     * @param response
     * @param accessDeniedException 拒绝访问的异常
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException, ServletException {

        // 回应401狀态
        log.info("\n>>>CustomAccessDeniedHandler handle\n");

        if (!response.isCommitted()) {
            String msg = accessDeniedException.getMessage();
            log.info("accessDeniedException.message: {}", msg);

            //设置响应状态标头为“未授权，不允许访问”
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE); //"application/json"

            Map<String, String> errors = new HashMap<>();
            errors.put("code", "403");
            errors.put("message", "权限不足!" + msg + "，请联系管理员。");

            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getOutputStream(), errors);
        }
    }
}
